import React, { useEffect, useState } from "react";
import { getAuthorArticleList } from "@/apis/userApi";
import { deleteArticle } from "@/apis/articlesApi.ts";
import { List, message, Modal } from "antd";
import { Article } from "@/apis/shared.ts";
import ArticleItem from "@/components/ArticleItem.tsx";

interface UserArticleListProps {
  isVertical: boolean;
}

const UserArticleList: React.FC<UserArticleListProps> = ({ isVertical }) => {
  const [articleList, setArticleList] = useState<Article[]>([]);
  const [articleToDelete, setArticleToDelete] = useState<string>("");
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 获取数据
  const fetchArticleListData = async () => {
    const res = await getAuthorArticleList();
    console.log("res at UserArticleList", res);
    setArticleList(res.data ? res.data : []);
  };

  // 显示删除弹窗
  const showModal = (articleId: string) => {
    setArticleToDelete(articleId);
    setIsModalOpen(true);
  };

  // 点击确定按钮
  const handleOk = async () => {
    // 如果要删除的文章ID为空，则直接返回
    if (!articleToDelete) {
      console.log("articleToDelete is null");
      return;
    }

    // 调用删除文章接口
    const res = await deleteArticle(articleToDelete);

    console.log("articleId at handleOk", articleToDelete);

    // 给用户一点提示
    message.success("删除文章成功");

    if (res.code === 200) {
      // 重新刷新一下文章列表
      fetchArticleListData();
    }

    // 清空要删除的文章的ID
    setArticleToDelete("");

    // 关闭弹窗
    setIsModalOpen(false);
  };

  // 点击取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 页面加载完成后，获取文章列表数据
  useEffect(() => {
    fetchArticleListData();
  }, []);

  return (
    <div>
      {/* 当articleList为空时显示Ant Design提供的Empty组件 */}
      {articleList.length === 0 ? (
        <div>暂无文章</div>
      ) : (
        <div>
          <List
            bordered
            itemLayout={isVertical ? "vertical" : "horizontal"}
            dataSource={articleList.length > 0 ? articleList : []}
            renderItem={(item) => (
              <ArticleItem
                item={item}
                setData={setArticleList}
                showModal={showModal}
              />
            )}
          />
          <Modal
            title="Basic Modal"
            open={isModalOpen}
            onOk={() => handleOk()}
            onCancel={() => handleCancel()}
          >
            <p>确定要删除该文章吗？</p>
          </Modal>
        </div>
      )}
    </div>
  );
};

export default UserArticleList;
